﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using ChampionsLeagueBets.Domain;
using ChampionsLeagueBets.Infrastructure;
using ChampionsLeagueBets.Web.Mvc.Authentication;
using ChampionsLeagueBets.Web.Mvc.Common;
using SharpArch.NHibernate.Contracts.Repositories;
using MvcContrib;
using SharpArch.NHibernate.Web.Mvc;

namespace ChampionsLeagueBets.Web.Mvc.Controllers
{
    public class PreferencesController : Controller
    {
		private readonly IExRepository<Setting> _settingRepository;
		private readonly IExRepository<SettingGroup> _settingGroupRepository;

		public PreferencesController(IExRepository<Setting> settingRepository, IExRepository<SettingGroup> settingGroupRepository)
    	{
    		_settingRepository = settingRepository;
    		_settingGroupRepository = settingGroupRepository;
    	}

        public ActionResult Edit()
        {
			if (!RightPrincipal.CurrentUser.IsAdmin) return this.RedirectToAction<HomeController>(c => c.NoRights());

			IList<SettingGroup> settingsGroups = _settingGroupRepository.GetAll();
			return View(settingsGroups);
        }

        [HttpPost]
		[Transaction]
		[ValidateAntiForgeryToken]
        public ActionResult Edit(FormCollection collection	)
        {
			if (!RightPrincipal.CurrentUser.IsAdmin) return this.RedirectToAction<HomeController>(c => c.NoRights());

            try
            {
            	for (int i = 0; i < collection.Count; ++i )
				{
					int id;
					if (Int32.TryParse(collection.AllKeys[i], out id))
					{
						Setting setting = _settingRepository.Get(id);
						setting.Value = collection[i];
					}
				}

				// Natychmiastowe odswiezenie ustawien aplikacji.
				var settingManagementService = new SettingManagementService();
				settingManagementService.LoadSettings(_settingRepository);

				TempData[ActionConfirmation.TempDataKey] = ActionConfirmation.CreateSuccess("Poprawnie zapisano ustawienia.");
            	return this.RedirectToAction<HomeController>(c => c.Administration());
            }
            catch
            {
				TempData[ActionConfirmation.TempDataKey] = ActionConfirmation.CreateSuccess("Błąd podczas zapisywanie ustawień.");
                return View();
            }
        }
    }
}
